//app.js
var com = require("./utils/common.js");
var util = require("./utils/util.js");
App({
  onLaunch: function () {
    var that = this;

    this.login();
    wx.setStorageSync('is_first', true); //重新登陆拦截 是否第一次登陆 true 第一次  false不是第一次
  },
  onShow() {

  },
  //四位一空格
  formatCard(str) {
    return str.replace(/\s/g, '').replace(/(\d{4})(?=\d)/g, "$1 ")
  },

  //清除所有个空格
  trimAll(str) {
    return str.replace(/\s*/g, '');
  },

  login() {
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        this.getOpenid(res.code);
      }
    });
  },

    //查询版本
    compareVersion(v1, v2) {
      v1 = v1.split('.')
      v2 = v2.split('.')
      const len = Math.max(v1.length, v2.length)
    
      while (v1.length < len) {
        v1.push('0')
      }
      while (v2.length < len) {
        v2.push('0')
      }
    
      for (let i = 0; i < len; i++) {
        const num1 = parseInt(v1[i])
        const num2 = parseInt(v2[i])
    
        if (num1 > num2) {
          return 1
        } else if (num1 < num2) {
          return -1
        }
      }
    
      return 0
    },
  
  //发起网络请求,获取openid,session_key
  getOpenid: function (code) {
    var that = this;
    that.ajax({
      url: 'User/Wx/getUserOpenid',
      method: "POST",
      data: {
        code: code
      },
      success: function (res) {
        wx.setStorageSync('openid', res.data.data.openid);
        wx.setStorageSync('session_key', res.data.data.session_key);
      }
    })
  },
  //获取token 
  getToken: function (code) {
    var that = this;
    var openid = wx.getStorageSync('openid');
    var nickName = wx.getStorageSync('nickName');
    var inviter_id = wx.getStorageSync('inviter_id');
    var lat = wx.getStorageSync('lat');
    var lng = wx.getStorageSync('lng');
    var phone = wx.getStorageSync('phone');
    var is_way = wx.getStorageSync('is_way'); //is_way==1 是授权登陆
    var sms_login = is_way == 2 ? true : false;
    console.log('打印的结果', sms_login, phone)
    wx.showLoading({
      title: '登录中...',
    })
    that.ajax({
      url: 'User/Login/register',
      method: "POST",
      data: {
        openid: openid,
        nickname: nickName,
        phone: phone,
        inviter_id: inviter_id,
        lat: lat,
        lng: lng,
        phone_code: code || '',
        sms_login: sms_login
      },
      success: function (res) {
        setTimeout(function () {
          wx.hideLoading()
        }, 2000)
        //对否登陆成功
        if (res.data.code == 1000) {
          wx.setStorageSync('token', res.data.data);
          wx.setStorageSync('is_login', true);
          var pages = getCurrentPages() //获取加载的页面
          var currentPage = pages[pages.length - 1] //获取当前页面的对象
          var url = currentPage.route //当前页面url
          console.log('当前页面', pages, url, is_way);
          if (url == 'pages/loginChoose/loginChoose' && is_way == 1 && pages.length <= 1) {
            wx.reLaunch({
              url: '/pages/home/home',
            })
            return
          }
          if (url == 'pages/login/login' && is_way == 2 && pages.length <= 2) {
            wx.reLaunch({
              url: '/pages/home/home',
            })
            return
          }
          //判断是否是当前页面
          if (url == 'pages/loginChoose/loginChoose' && is_way == 1) {
            wx.navigateBack({
              delta: 1
            })
          } else if (url == 'pages/login/login' && is_way == 2) {
            console.log('当前页面返回二2222222');
            wx.navigateBack({
              delta: 2
            })
          } else {
            // wx.reLaunch({
            //   url: '/pages/home/home',
            // })
            currentPage.onLoad();
            currentPage.onShow();
          }


        } else {
          var pages = getCurrentPages() //获取加载的页面
          var currentPage = pages[pages.length - 1] //获取当前页面的对象
          var url = currentPage.route //当前页面url
          if (url == 'pages/loginChoose/loginChoose') {
            return
          } else {
            wx.navigateTo({
              url: '/pages/loginChoose/loginChoose',
            })
          }
        }
      }
    })
  },
  //弹窗MODEL
  showModal(title = "提示", content = "", success = function () {}) {
    wx.showModal({
      title: title,
      content: content,
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          success();
        } else if (res.cancel) {

        }
      }
    })
  },
  //跳转到其他小程序
  navigateToMiniProgram(appId, path, extraData = {}, envVersion = 'release') {
    wx.navigateToMiniProgram({
      appId: appId,
      path: path,
      extraData: extraData,
      envVersion: envVersion, //trial体验版release正式版
      success(res) {
        console.log('success', res);
      },
      fail(e) {
        console.log('error', e);
      }
    })
  },
  //ajax 请求
  ajax(model) {
    var that = this;
    if (util.isExitsVariable(model.load)) {
      var msg = "加载中";
      if (util.isExitsVariable(model.msg)) {
        msg = model.msg;
      }
      wx.showLoading({
        title: msg,
      })
    }
    if (!util.isExitsVariable(model.method)) {
      model.method = "POST";
    }
    // 判断请求哪个接口
    if (model.url_type == 1) {
      //拼接url model.url_type == 1  仅代表Boss后台请求
      if (model.url.indexOf("https://") == -1 && model.url.indexOf("http://") == -1) {
        model.url = this.globalData.boss_url + model.url;
      }
    } else {
    //拼接url
    if (model.url.indexOf("https://") == -1 && model.url.indexOf("http://") == -1) {
      model.url = this.globalData._url + model.url;

    }
    }
    //get参数拼接
    if (model.method == "get" && model.data !== undefined) {
      for (let k in model.data) {
        if (model.data[k].toString() !== '') {
          model.url = model.url + "&" + k + "=" + model.data[k];
        }
      }
      model.data = '';
    }
    //返回Promise对象
    return new Promise(
      function (resolve) {
        var token = wx.getStorageSync('token');
        var openid = wx.getStorageSync('openid');
        wx.request({
          method: model.method,
          url: model.url,
          header: {
            'token': token, // 默认值
            'openid': openid,
            "Company-No": that.globalData.company_no,
          },
          data: model.data,
          success: (resolve) => {
            if (util.isExitsVariable(model.load)) {
              wx.hideLoading();
            }
            if (resolve.data.code == -1004) {
              wx.setStorageSync('is_login', false);
              var is_first = wx.getStorageSync('is_first');
              if (is_first) {
                wx.setStorageSync('is_first', false);
                that.login();
                that.getToken();
              }
              return;
            }
            model.success(resolve);

          },
          error: () => {
            model.error('网络请求失败');
          }
        })
      }
    )
  },
  globalData: {
    userInfo: null,
    company_no:20001,//公司编号,提交版本时注意确认
    _url: "https://water.youheone.com/",
    boss_url: 'https://boss.youheone.com/',
    //wxe3989937410512f8
    // _url: 'https://waterapi.wechat-app.me/',
    // boss_url: 'https://test.cqthesis.cn/',
    //wx73abd91260a9976e
    cloud_user_appid: 'wx76e19f9eb5bcb658', //优净云用户端小程序APPID 
    article_column_code: { 'JK': 'JK0001', 'HD': 'HD0001', 'CZ': 'CZ0001', 'GY': 'GY0001', 'JF': 'JF0001', 'RW':'TPXAG0U5'},//文章栏目,JK:健康话题,HD:活动,CZ:充值卡规则,GY：关于我们,JF:积分规则
  },
  //弹窗toast
  showToast(title = "", icon = "none", duration = 1000, complete = function () {}) {
    wx.showToast({
      title: title,
      icon: icon,
      duration: duration,
      complete: function (res) {
        complete();
      }
    })
    return false;
  },

  //
})
